package com.test.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.oltu.oauth2.as.issuer.MD5Generator;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuer;
import org.apache.oltu.oauth2.as.issuer.OAuthIssuerImpl;
import org.apache.oltu.oauth2.as.request.OAuthTokenRequest;
import org.apache.oltu.oauth2.as.response.OAuthASResponse;
import org.apache.oltu.oauth2.common.exception.OAuthProblemException;
import org.apache.oltu.oauth2.common.exception.OAuthSystemException;
import org.apache.oltu.oauth2.common.message.OAuthResponse;
import org.apache.oltu.oauth2.common.message.types.TokenType;

public class RefreshTokenServlet extends HttpServlet {

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		super.doGet(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		OAuthTokenRequest oauthRequest = null;
		OAuthIssuer oauthIssuerImpl = new OAuthIssuerImpl(new MD5Generator());

		try {
			oauthRequest = new OAuthTokenRequest(request);
			validateClient(oauthRequest);
			
			String accessToken = oauthIssuerImpl.accessToken();

			saveTokenToDB(oauthIssuerImpl);
			
			// some code
			OAuthResponse r = OAuthASResponse
					.tokenResponse(HttpServletResponse.SC_OK)
					.setAccessToken(accessToken).setExpiresIn("3600")
					.setTokenType(TokenType.BEARER.toString()).buildJSONMessage();

			response.setStatus(r.getResponseStatus());
			response.setHeader("Cache-Control", "no-store");
			response.setHeader("Pragma", "no-cache");
			response.setHeader("Content-Type", "application/json;charset=UTF-8");
			PrintWriter pw = response.getWriter();((HttpServletRequest) response).getHeaderNames();
			pw.print(r.getBody());
			pw.flush();
			pw.close();
			// if something goes wrong
		} catch (OAuthProblemException ex) {

			OAuthResponse r;
			try {
				r = OAuthResponse.errorResponse(401).error(ex)
						.buildJSONMessage();
				response.setStatus(r.getResponseStatus());
				response.setHeader("Cache-Control", "no-store");
				response.setHeader("Pragma", "no-cache");
				response.setHeader("Content-Type", "application/json;charset=UTF-8");
				PrintWriter pw = response.getWriter();
				pw.print(r.getBody());
				pw.flush();
				pw.close();
				response.sendError(401);
			} catch (OAuthSystemException e) {
				e.printStackTrace();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void validateClient(OAuthTokenRequest oauthRequest) {
		// TODO Auto-generated method stub
		
	}

	private void saveTokenToDB(OAuthIssuer oauthIssuerImpl) {
		// TODO Auto-generated method stub
		
	}

}
